#define _CRT_SECURE_NO_WARNINGS 1
#define _CRT_SECURE_NO_WARNINGS 1

#include "queue.h"

void QInit(Queue* pq)
{
	assert(pq);

	pq->tail = NULL;
	pq->head = NULL;
	pq->size = 0;

}

void QDestroy(Queue* pq)
{
	assert(pq);

	QNode* cur = pq->head;
	while (cur)
	{
		QNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->head = NULL;
	pq->tail = NULL;
	pq->size = 0;
}

int QSize(Queue* pq)
{
	assert(pq);

	return pq->size;
}

bool QEmpty(Queue* pq)
{
	assert(pq);

	return pq->head == NULL && pq->tail == NULL;
}

void QPush(Queue* pq, QDatatype x)
{
	assert(pq);

	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc fail\n");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;

	if (pq->head == NULL)
	{
		assert(pq->tail == NULL);
		pq->head = pq->tail = newnode;

	}

	else
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}
	pq->size++;
}

void QPop(Queue* pq)
{
	assert(pq);
	assert(!QEmpty(pq));

	QNode* cur = pq->head;
	QNode* next = cur->next;
	free(cur);
	pq->head = next;
	if (pq->head == NULL)
	{
		pq->tail = NULL;
	}

	/*if (pq->head->next == NULL)
	{
		free(pq->head);
		pq->head = pq->tail = NULL;
	}

	else
	{
		QNode* cur = pq->head;
		QNode* next = cur->next;
		free(cur);
		pq->head = next;
	}*/
	pq->size--;
}

QDatatype QBack(Queue* pq)
{
	assert(pq);
	assert(!QEmpty(pq));

	return pq->tail->data;
}

QDatatype QFront(Queue* pq)
{
	assert(pq);
	assert(!QEmpty(pq));

	return pq->head->data;
}

